C++ union 与 reinterpret_cast
全部标签 在阅读GCC对std::optional的实现时,我注意到了一些有趣的事情。我知道boost::optional实现如下:templateclassoptional{//...private:boolhas_value_;aligned_storagestorage_;}但是libstdc++和libc++(以及Abseil)都像这样实现它们的可选类型:templateclassoptional{//...private:structempty_byte{};union{empty_byteempty_;Tvalue_;};boolhas_value_;}在我看来,它们在功能上是相同的
我希望有人能准确阐明C++中未定义行为的含义。给定以下类定义:classFoo{public:explicitFoo(intValue):m_Int(Value){}voidSetValue(intValue){m_Int=Value;}private:Foo(constFoo&rhs);constFoo&operator=(constFoo&rhs);private:intm_Int;};如果我理解正确,下面代码中指向引用和指针的两个const_casts将删除Foo类型的原始对象的常量性,但是通过指针或引用将导致未定义的行为。intmain(){constFooMyConstFoo
#includeusingnamespacestd;classX{public:virtualvoidf(){}};classY{public:virtualvoidg(){}};intmain(){X*x=newX();Y*y=dynamic_cast(x);//A//Y*y=static_cast(x);//BcoutA编译而B不编译。我明白为什么B没有被编译但是为什么A被编译虽然X和Y是完全不相关的类型? 最佳答案 这就是为什么dynamic_cast在不相关的类型之间被允许:classX{public:virtualvoid
我可能发现了GCCv4.8.2的错误,但我想在提交之前先检查一下,因为这可能是我做错了什么!以下代码:#includestructMessage{typedefunion{charbyte;constchar*str;}Parameter;Parameterp1;Parameterp2;};intmain(){std::vectormessages_;messages_.push_back({{.byte='a'}});Messagemessage={{.byte='a'},{.str="HelloWorld"}};messages_.push_back(message);messag
死的简单Thrift联盟的例子。环境:最新的thrift,cpp作为服务器,java作为客户端mytest.thrift:namespacejavacom.wilbeibi.thriftunionValue{1:i16i16_v,2:stringstr_v,}structBox{1:Valuevalue;}serviceMyTest{BoxechoUnion(1:i32number);}C++服务器代码:#include"MyTest.h"#include#include#include#includeusingnamespace::apache::thrift;usingnamesp
来自C++标准:5.2.10.3Themappingperformedbyreinterpret_castmight,ormightnot,producearepresentationdifferentfromtheoriginalvalue.我在这个网站接受过培训,相信并重复这一点。(即使可能只是琐事)。从float*到int*的reinterpret_cast被允许产生不同的位模式。唯一的保证是reinterpret_cast将结果返回到float*将产生原始位模式。我的问题:这会发生吗?是否存在实际reinterpret_cast为不同位模式的现有真实平台或CPU或编译器?如果不
今天我遇到了一个我似乎无法解决的问题。我正在编译一个共享库,其中包含一个模板化类(Derived,其基础是Base)和此类的一些显式实例化。我希望图书馆用户从这个模板化类中扩展。当我尝试dynamic_cast时出现问题来自Base*的用户实例至Derived*.我已经将问题缩小到这个MWE:共享库包含以下文件:Base.h#ifndefBASE_H_#defineBASE_H_classBase{public:Base();virtual~Base();};#endif/*BASE_H_*/Derived.h#ifndefDERIVED_H_#defineDERIVED_H_#inc
这个问题在这里已经有了答案:Operatorcast,GCCandclang:whichcompilerisright?(1个回答)关闭6年前。考虑以下程序:structS{usingT=float;operatorT(){return9.9f;}};intmain(){Sm;S::Tt=m;t=m.operatorT();//Isthiscorrect?}程序在g++中编译良好(参见现场演示here)但它在clang++、MSVC++和IntelC++编译器中编译失败clang++给出以下错误(参见现场演示here)main.cpp:8:20:error:unknowntypenam
是什么让union成员活跃起来?我已经阅读了C++14标准的第9.5章(关于union的那一章),但是对于什么使union成员活跃,我还没有找到明确的答案。有一个注释:Ingeneral,onemustuseexplicitdestructorcallsandplacementnewoperatorstochangetheactivememberofaunion.例如,unionU{inti;shorts;}u;new(&u.i)int(42);好的,placementnew改变了activemember,很清楚了。但是在处理具有普通构造函数的类型时,我们通常不使用placementn
考虑以下代码:unionU{inta;floatb;};intmain(){Uu;int*p=&u.a;*(float*)p=1.0f;//我们都知道union字段的地址通常是相同的,但我不确定这样做是否是明确定义的行为。因此,问题是:像上面的代码一样强制转换和取消引用指向union字段的指针是否合法且定义明确的行为?附言我知道它更像是C语言而不是C++,但我想了解它在C++中是否合法,而不是C。 最佳答案 联盟的所有成员必须位于同一地址,这是标准所保证的。您正在做的确实是明确定义的行为,但应该注意的是,您不能使用相同的方法从uni